<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\Config;
use app\admin\model\UserGroup;
use app\admin\model\User as UserModel;
use app\admin\validate\User as UserValidate;
/**
 * 用户管理
 */
class User extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input  = input();
            $order  = $input['order'] === 'ascending' ? 'asc' : 'desc';
            $count  = UserModel::withSearch(['keyword','date'], $input)->count();
            $data   = UserModel::withSearch(['keyword','date'], $input)
            ->with(['group'])
            ->order($input['prop'], $order)
            ->page($input['page'], $input['pageSize'])
            ->select();
            return json(['status' => 'success', 'message' => '', 'data' => $data, 'count' => $count]);
        } else {
            $event = event("UserField");
            $field = [];
            foreach ($event as $key => $val) {
                foreach ($val as $k => $v) {
                    if (isset($v['indexShow']) && $v['indexShow']) {
                        array_push($field, $v);
                    }
                }
            }
            $group  = UserGroup::where('status', 1)->select();
            $config = Config::getVal('user');
            View::assign([
                'group'  => $group, 
                'config' => $config,
                'field'  => $field,
            ]);
            return View::fetch();
        }
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('save')->check($input);
            $account = UserModel::where('account', $input['account'])->value('id');
            $mobile  = UserModel::where('mobile', $input['mobile'])->value('id');
            $email   = UserModel::where('email', $input['email'])->value('id');
            if (! $account) {
                if (! $email) {
                    if (! $mobile) {
                        $integral = UserGroup::where('id', $input['group_id'])->value('integral');
                        $date  = date('Y-m-d H:i:s');
                        UserModel::create([
                            'group_id'         => $input['group_id'],
                            'nickname'         => $input['nickname'],
                            'sex'              => $input['sex'],
                            'email'            => $input['email'],
                            'mobile'           => $input['mobile'],
                            'account'          => $input['account'],
                            'password'         => $input['password'],
                            'pay_paasword'     => '',
                            'cover'            => $input['cover'],
                            'describe'         => $input['describe'],
                            'birthday'         => $input['birthday'],
                            'now_integral'     => $integral,
                            'history_integral' => $integral,
                            'balance'          => $input['balance'],
                            'login_ip'         => "",
                            'login_count'      => 0,
                            'login_time'       => $date,
                            'update_time'      => $date,
                            'create_time'      => $date,
                            'status'           => $input['status'],
                            'see'              => 0,
                            'field'            => $input['field'],
                        ]);
                        return json(['status' => 'success', 'message' => '新增成功']);
                    } else {
                        return json(['status' => 'error', 'message' => '手机号已经存在！']);
                    }
                } else {
                    return json(['status' => 'error', 'message' => '邮箱号已经存在！']);
                }
            } else {
                return json(['status' => 'error', 'message' => '账号已经存在！']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(UserValidate::class)->check($input);
            $save  = UserModel::find($input['id']);
            $save->update_time = date('Y-m-d H:i:s');
            // 分组发生改变
            $integral = UserGroup::where('id', $input['group_id'])->value('integral');
            if ($input['group_id'] != $save->group_id) {
                $save->history_integral = $integral;
            }
            $save->now_integral = $input['now_integral'];
            $save->group_id     = $input['group_id'];
            $save->nickname     = $input['nickname'];
            $save->sex          = $input['sex'];
            $save->cover        = $input['cover'];
            $save->describe     = $input['describe'];
            $save->birthday     = $input['birthday'];
            $save->balance      = $input['balance'];
            $save->status       = $input['status'];
            $save->field        = $input['field'];
            if (! empty($input['password'])) {
                $save->password = $input['password'];
            }
            $save->save();
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $input = input();
            validate(UserValidate::class)->scene('delete')->check($input);
            UserModel::destroy($input['ids']);
            return json(['status' => 'success', 'message' => '删除成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
}
